package com.hengxinguotong.zhihuichengjian.ui.quality;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.app.Fragment;
import android.support.v4.view.ViewPager;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.widget.RadioButton;
import android.widget.RelativeLayout;

import com.google.gson.Gson;
import com.hengxinguotong.zhihuichengjian.R;
import com.hengxinguotong.zhihuichengjian.adapter.MyFragmentPagerAdapter;
import com.hengxinguotong.zhihuichengjian.bean.MenuBean;
import com.hengxinguotong.zhihuichengjian.bean.MenuListRes;
import com.hengxinguotong.zhihuichengjian.bean.RectificationCountRes;
import com.hengxinguotong.zhihuichengjian.ui.BaseActivity;
import com.hengxinguotong.zhihuichengjian.utils.Constants;
import com.hengxinguotong.zhihuichengjian.utils.SPUtil;
import com.hengxinguotong.zhihuichengjian.utils.Utils;
import com.hengxinguotong.zhihuichengjian.widget.font.HXTextView;
import com.hengxinguotong.zhihuichengjian.widget.view.MyRadioGroup;
import com.lidroid.xutils.http.RequestParams;

import org.apache.http.entity.StringEntity;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * 整改列表
 * Created by liux on 2017/3/27.
 */

public class RectificationListActivity extends BaseActivity implements ViewPager.OnPageChangeListener{

    private static final String TAG = "RectificationList";
    @BindView(R.id.iv_back)
    HXTextView ivBack;
    @BindView(R.id.title_tv)
    HXTextView titleTv;
    @BindView(R.id.rl_title)
    RelativeLayout rlTitle;
    @BindView(R.id.daizhenggai)
    RadioButton daizhenggai;
    @BindView(R.id.daizhenggai_tv)
    HXTextView daizhenggaiTv;
    @BindView(R.id.daifujian)
    RadioButton daifujian;
    @BindView(R.id.daifujian_tv)
    HXTextView daifujianTv;
    @BindView(R.id.nopass)
    RadioButton nopass;
    @BindView(R.id.nopass_tv)
    HXTextView nopassTv;
    @BindView(R.id.yizhenggai)
    RadioButton yizhenggai;
    @BindView(R.id.myradiogroup)
    MyRadioGroup myradiogroup;
    @BindView(R.id.rectification_vp)
    ViewPager rectification_vp;
    public static final int UPDATE = 1001;
    private int type;
    private List<MenuBean> menuList;//
    private List<Fragment> fragments;
    private RectificationListFragment daizhenggaiFragment,daifujianFragment,butongguoFragment,yizhenggaiFragment;
    private int currentpageItem = 1 ;

    private Handler handler = new Handler(){
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what){
                case 0:
                    RectificationCountRes rectificationCountRes = (RectificationCountRes) msg.obj;
                    if (rectificationCountRes.getValue().getWaitCorrectiveCount() != 0) {
                        daizhenggaiTv.setVisibility(View.VISIBLE);
                        if(rectificationCountRes.getValue().getWaitCorrectiveCount() > 99){
                            daizhenggaiTv.setText("99+");
                        }else{
                            daizhenggaiTv.setText(rectificationCountRes.getValue().getWaitCorrectiveCount() + "");
                        }
                    } else {
                        daizhenggaiTv.setVisibility(View.GONE);
                    }

                    if (rectificationCountRes.getValue().getWaitCheckCount() != 0) {
                        daifujianTv.setVisibility(View.VISIBLE);
                        if(rectificationCountRes.getValue().getWaitCheckCount() > 99){
                            daifujianTv.setText("99+");
                        }else{
                            daifujianTv.setText(rectificationCountRes.getValue().getWaitCheckCount() + "");
                        }
                    } else {
                        daifujianTv.setVisibility(View.GONE);
                    }

                    if (rectificationCountRes.getValue().getCheckNoPassCount() != 0) {
                        nopassTv.setVisibility(View.VISIBLE);
                        if(rectificationCountRes.getValue().getCheckNoPassCount() > 99){
                            nopassTv.setText("99+");
                        }else{
                            nopassTv.setText(rectificationCountRes.getValue().getCheckNoPassCount() + "");
                        }
                    } else {
                        nopassTv.setVisibility(View.GONE);
                    }
                    break;
            }
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_rectification_list);
        ButterKnife.bind(this);
        type = getIntent().getIntExtra("type", Constants.QUALITY);
        initView();
    }

    private void initView() {
        String authority = SPUtil.getString(this, "authority");
        if(!Utils.isEmpty(authority)){
            try{
                MenuListRes menuListRes = new Gson().fromJson(authority, MenuListRes.class);
                menuList = menuListRes.getValue();
            }catch (Exception e){
                Log.e(TAG, e.getMessage().toString());
            }
        }
        if(menuList == null){
            menuList = new ArrayList<>();
        }

        switch (type) {
            case Constants.QUALITY:
                titleTv.setText("质量整改列表");
                for (MenuBean menu:menuList){
                    if(menu.getId() == 300){
                        menu.setHasNew(false);
                        for(MenuBean sMenu:menu.getData()){
                            if(sMenu.getId() == 330){
                                sMenu.setHasNew(false);
                            }
                        }
                    }
                }
                break;
            case Constants.SECURITY:
                titleTv.setText("安全整改列表");
                for (MenuBean menu:menuList){
                    if(menu.getId() == 400){
                        menu.setHasNew(false);
                        for(MenuBean sMenu:menu.getData()){
                            if(sMenu.getId() == 430){
                                sMenu.setHasNew(false);
                            }
                        }
                    }
                }
                break;
            case Constants.LIVE:
                type = Constants.QUALITY;
                titleTv.setText("现场整改列表");
                for (MenuBean menu:menuList){
                    if(menu.getId() == 1500){
                        menu.setHasNew(false);
                        for(MenuBean sMenu:menu.getData()){
                            if(sMenu.getId() == 1520){
                                sMenu.setHasNew(false);
                            }
                        }
                    }
                }
                break;
            case Constants.QUALITY_SUPERVISE:
                titleTv.setText("质量整改列表");
                for (MenuBean menu:menuList){
                    if(menu.getId() == 51){
                        menu.setHasNew(false);
                        for(MenuBean sMenu:menu.getData()){
                            if(sMenu.getId() == 52){
                                sMenu.setHasNew(false);
                            }
                        }
                    }
                }
                break;
            case Constants.SECURITY_SUPERVISE:
                titleTv.setText("安全整改列表");
                for (MenuBean menu:menuList){
                    if(menu.getId() == 53){
                        menu.setHasNew(false);
                        for(MenuBean sMenu:menu.getData()){
                            if(sMenu.getId() == 54){
                                sMenu.setHasNew(false);
                            }
                        }
                    }
                }
                break;
            case Constants.CIVILIZED_CONSTRUCTION_SUPERVISE:
                titleTv.setText("文明施工整改列表");
                for (MenuBean menu:menuList){
                    if(menu.getId() == 55){
                        menu.setHasNew(false);
                        for(MenuBean sMenu:menu.getData()){
                            if(sMenu.getId() == 56){
                                sMenu.setHasNew(false);
                            }
                        }
                    }
                }
                break;
        }
        MenuListRes res = new MenuListRes();
        res.setValue(menuList);
        authority = new Gson().toJson(res);
        SPUtil.put(this, "authority", authority);
        Intent intent = new Intent();
        intent.setAction("update_menu");
        sendBroadcast(intent);

        myradiogroup.check(R.id.daizhenggai);
        initViewPager();
        getRectificationCount();
        myradiogroup.setOnCheckedChangeListener(new MyRadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(MyRadioGroup group, int checkedId) {
                switch (checkedId) {
                    case R.id.daizhenggai:
                        rectification_vp.setCurrentItem(0);
                        break;
                    case R.id.daifujian:
                        rectification_vp.setCurrentItem(1);
                        break;
                    case R.id.nopass:
                        rectification_vp.setCurrentItem(2);
                        break;
                    case R.id.yizhenggai:
                        rectification_vp.setCurrentItem(3);
                        break;
                }

            }
        });
    }

    private void initViewPager(){
        fragments = new ArrayList<Fragment>();
        if(daizhenggaiFragment == null){
            daizhenggaiFragment = RectificationListFragment.newInstance(type, "1");
        }
        fragments.add(daizhenggaiFragment);
        if(daifujianFragment == null){
            daifujianFragment = RectificationListFragment.newInstance(type, "2");
        }
        fragments.add(daifujianFragment);
        if(butongguoFragment == null){
            butongguoFragment = RectificationListFragment.newInstance(type, "3");
        }
        fragments.add(butongguoFragment);
        if(yizhenggaiFragment == null){
            yizhenggaiFragment = RectificationListFragment.newInstance(type, "4");
        }
        fragments.add(yizhenggaiFragment);
        rectification_vp.setAdapter(new MyFragmentPagerAdapter(getSupportFragmentManager(), fragments));
        currentpageItem = getIntent().getIntExtra("status", 1);//1:待受理; 2:处理中;3:待检查;4:检查不通过；5:已完成
        if(currentpageItem == 4){
            currentpageItem = 1;
        }else if(currentpageItem == 5){
            currentpageItem = 4;
        }
        rectification_vp.setCurrentItem(currentpageItem - 1);
        switch (currentpageItem - 1){
            case 0:
                myradiogroup.check(R.id.daizhenggai);
                break;
            case 1:
                myradiogroup.check(R.id.daifujian);
                break;
            case 2:
                myradiogroup.check(R.id.nopass);
                break;
            case 3:
                myradiogroup.check(R.id.yizhenggai);
                break;
        }
        rectification_vp.addOnPageChangeListener(this);
    }

    @OnClick({R.id.iv_back})
    public void onClick(View view) {
        Intent intent;
        switch (view.getId()) {
            case R.id.iv_back:
                setResult(0);
                finish();
                break;
        }
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if(keyCode == KeyEvent.KEYCODE_BACK){
            setResult(0);
            finish();
        }
        return super.onKeyDown(keyCode, event);
    }

    public void getRectificationCount() {
        JSONObject jsonObject = new JSONObject();
        try {
            jsonObject.put("constructionId", SPUtil.getString(this, "constructionid"));
            if (!hasList()) {
                jsonObject.put("contactId", SPUtil.getString(this, "userId"));
            }
            jsonObject.put("type", type);
        } catch (JSONException e) {
            e.printStackTrace();
        }

        RequestParams params = new RequestParams();
        params.addHeader("Content-type", "application/json");
        try {
            params.setBodyEntity(new StringEntity(jsonObject.toString(), "UTF-8"));
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        Utils.requestData(null, this, "/inspection/queryCount/" + SPUtil.getString(this, "uuid"), params, new Utils.ListenerJson() {
            @Override
            public void onSuccess(String json) {
                if (!Utils.isEmpty(json)) {
                    Gson gson = new Gson();
                    RectificationCountRes rectificationCountRes = gson.fromJson(json, RectificationCountRes.class);
                    Message msg = handler.obtainMessage();
                    msg.what = 0;
                    msg.obj = rectificationCountRes;
                    msg.sendToTarget();
                }
            }

            @Override
            public void onFailure(String json) {
            }
        });
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == UPDATE) {
            for(Fragment fragment:fragments){
                ((RectificationListFragment)fragment).reLoad();
            }
            getRectificationCount();
        }
    }

    @Override
    public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

    }

    @Override
    public void onPageSelected(int position) {
        switch (position){
            case 0:
                myradiogroup.check(R.id.daizhenggai);
                break;
            case 1:
                myradiogroup.check(R.id.daifujian);
                break;
            case 2:
                myradiogroup.check(R.id.nopass);
                break;
            case 3:
                myradiogroup.check(R.id.yizhenggai);
                break;
        }
        currentpageItem = rectification_vp.getCurrentItem();
    }

    @Override
    public void onPageScrollStateChanged(int state) {

    }
}
